package com.example.workmode.AppManager;


import java.util.List;

import com.example.workmode.R;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

public class AppAdapter extends ArrayAdapter<ApplicationInfo>{

	private List<ApplicationInfo> appList = null;
	private Context context;
	private SharedPreferences pref;
	private PackageManager packageManager;
	
	public AppAdapter(Context context, int resource,
			List<ApplicationInfo> objects) {
		super(context, resource, objects);
		
		this.context = context;
		this.appList = objects;
		packageManager = context.getPackageManager();
	}
	
	@Override
	public int getCount() {
		return ((null != appList) ? appList.size() : 0);
	}
	
	@Override
	public ApplicationInfo getItem(int position) {
		return ((null != appList) ? appList.get(position) : null);
	}
	
	@Override
	public long getItemId(int position) {
		return position;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		
		if(null == view) {
			LayoutInflater layoutInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = layoutInflater.inflate(R.layout.app_row_layout, null);
		}
		
		ApplicationInfo data = appList.get(position);
		
		if(null != data) {
			//TextView appName = (TextView) view.findViewById(R.id.app_name);
			//TextView packageName = (TextView) view.findViewById(R.id.app_package);
			ImageView iconView = (ImageView) view.findViewById(R.id.app_icon);
			CheckedTextView chkBshow = (CheckedTextView) view.findViewById(R.id.check);
			//appName.setText(data.loadLabel(packageManager));
			//packageName.setText(data.packageName);
			chkBshow.setText(data.loadLabel(packageManager));
			pref = getContext().getSharedPreferences("MyPrefs", 0);
        	String blockingApps = pref.getString("blockingApps", ";");
			if(blockingApps.contains(data.packageName)) {
				chkBshow.setChecked(true);
			} else {
				chkBshow.setChecked(false);
			}
			iconView.setImageDrawable(data.loadIcon(packageManager));
		}
		return view;
	}
}
